<template>
    <div class="edu-page-warp">
        <el-card shadow="never" body-style="padding: 24px;">
            <el-row>
                <el-col>
                    <div class="tagTitle">先修课标签维护</div>
                </el-col>
            </el-row>
            <el-row style="margin-bottom:30px;">
                <el-col>
                    <div class="divLeft">
                        <el-input
                            placeholder="请输入标签名称"
                            v-model="searchForm.tagName"
                            style="width:240px;"
                            @change="search"
                            @keyup.enter.native="search"
                        >
                            <i
                                slot="prefix"
                                class="el-icon-search"
                                style="margin-top:10px;cursor:pointer"
                                @click="search"
                            ></i>
                        </el-input>
                    </div>
                    <div class="divRight">
                        <el-button type="primary" @click="addPreTagInfo">新增</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-table :data="tableData" style="width:100%" tooltip-effect="light">
                    <el-table-column prop="prerequisiteTagName" label="标签名称" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createPerson" label="创建人" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createDate" label="创建时间" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="courseName" label="课程范围" show-overflow-tooltip></el-table-column>
                    <el-table-column label="启用状态" prop="majorFlag">
                        <template slot-scope="scope">
                            <el-tag v-if="scope.row.majorFlag*1 == 1" type="success" size="mini">启用</el-tag>
                            <el-tag v-else type="danger" size="mini">停用</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="option" label="操作" min-width="60" fixed="right">
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
                            <el-button type="text" size="small" @click="deleteTag(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <div style="margin: 18px 0;">
                <div style="float:right;">
                    <el-pagination
                        v-nocursor
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        @keyup.enter.native.self.stop="e=>{handleCurrentChange(e.target.value)}"
                        :current-page="page.currentPage"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="page.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="page.totalPage"
                    ></el-pagination>
                </div>
            </div>
        </el-card>
        <el-dialog
            :title="`(${!dialogTiltle?'新增':'修改'}辅修先修课标签）辅修标签维护`"
            :visible.sync="dialogTagVisible"
            width="55%"
            :close-on-click-modal="false"
        >
            <el-form :model="tagForm" ref="tagForm" :rules="checkFormRules" label-width="148px">
                <el-form-item label="标签名称" prop="tagName">
                    <el-col :span="16" class="rightCol">
                        <el-input v-model="tagForm.tagName" autocomplete="off" :placeholder="$t('common.pla.pleaseInput')"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item :label="$t('minor.major.college')" prop="faculty">
                    <el-col :span="16" class="rightCol">
                        <el-select
                            clearable
                            filterable
                            v-model="tagForm.faculty"
                            @change="queryCourse"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in options.faculty"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="先修课名称" prop="courses">
                    <el-col :span="16" class="rightCol">
                        <!-- <el-select
                            v-model="tagForm.courses"
                            multiple
                            filterable
                            clearable
                            placeholder="请选择课程"
                            style="width:100%;"
                        >
                            <el-option
                                v-for="item in options.courses"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select> -->
                        <el-select
                            v-model="tagForm.courses"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入课程代码"
                            :remote-method="remoteMethod"
                            style="width:100%;"
                            :loading="loading">
                                <el-option
                                    v-for="item in options.courses"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-col :span="16" class="rightCol">
                        <el-switch
                            style="vertical-align: baseline;"
                            v-model="tagForm.startStatus"
                            active-color="#13ce66"
                            active-text="是"
                            inactive-text="否"
                        ></el-switch>
                    </el-col>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogTagVisible = false">取 消</el-button>
                <el-button type="primary" v-show="updateButton" @click="updateCourseTagInfo">确 定</el-button>
                <el-button type="primary" v-show="insertButton" @click="confirmInfo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    findPrerequisiteCourseTagList,
    insertTagInfo,
    queryCourseInfo,
    deleteTagInfo,
    updatePreCourseTagInfo,
     findAllDeptList
} from "common/src/api/minor/prerequisiteCourseTag";
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
import * as INDEX from "common/src/utils/index";
import nocursor from "common/src/directives/nocursor";
import mixin from 'common/src/mixins/index';
export default {
    mixins: [mixin],
    data() {
        return {
            dialogTiltle: 0,
            updateButton: false,
            insertButton: false,
            rowTagId: "",
            searchForm: {
                tagName: ""
            },
            dialogTagVisible: false,
            tagForm: {
                tagName: "",
                faculty: "",
                major: "",
                preCourseName: "",
                startStatus: true,
                courses: [],
                oldTagName: ""
            },
            options: {
                faculty: [],
                courses: []
            },
            page: {
                currentPage: 1,
                pageSize: 20,
                totalPage: 0
            },
            tableData: [],
            checkFormRules: {
                tagName: [
                    {
                        required: true,
                        message: "请输入标签名称",
                        trigger: "blur"
                    }
                ],
                faculty: [
                    { required: true, message: this.$t('minor.tip.collegeTip'), trigger: "change" }
                ],
                courses: [
                    { required: true, message: "请选择课程", trigger: "change" }
                ]
            },
            loading: false
        };
    },
    directives: {
        nocursor
    },
    mounted: function() {
        if (!this.$checkMinor()) return;
        this.findPreCourseTagList({
            tagName: "",
            pageNum: 1,
            pageSize: 20
        });
        this.initCollege();
    },
    methods: {
        initCollege() {
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_YX"]
            };
            queryDic(data).then(res => {
                this.options.faculty = [];
                UTILS.fillSelect(
                    {
                        faculty: "X_YX"
                    },
                    res.data,
                    this.options
                );
            });
        //     findAllDeptList().then(({code,data})=>{
        //        if(code!=200)return;
        //        data.forEach((value)=>{
        //          this.options.faculty.push({
        //            key:value.deptCode,
        //            label:value.deptName,
        //            value:value.deptCode
        //        })
        //        })
               
        //    })
        },
        // 新增
        addPreTagInfo() {
            if (!this.$checkMinor()) return;
            this.tagForm = {
                tagName: "",
                faculty: "",
                major: "",
                preCourseName: "",
                startStatus: true,
                courses: []
            };
            this.dialogTagVisible = true;
            this.updateButton = false;
            this.insertButton = true;
            this.options.courses = [];
            this.$refs.tagForm && this.$refs.tagForm.resetFields();
            if (this.global.isAcdemicDean) {
                this.tagForm.faculty = this.options.faculty[0] && this.options.faculty[0].value;
            }
        },
        confirmInfo() {
            this.$refs.tagForm.validate(valid => {
                if (valid) {
                    this.dialogTiltle = 0;
                    let params = {
                        tagName: this.tagForm.tagName,
                        collegeId: this.tagForm.faculty,
                        courseId: this.tagForm.courses.toString(),
                        tagFlag: this.tagForm.startStatus ? "1" : "0",
                        majorId: 0
                    };
                    insertTagInfo(params).then(res => {
                        if (res.code == 200) {
                            this.dialogTagVisible = false;
                            this.$message({
                                type: "success",
                                message: "新增成功"
                            });
                            this.findPreCourseTagList({
                                tagName: "",
                                pageNum: 1,
                                pageSize: 20
                            });
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        handleCurrentChange(val) {
            this.searchForm.pageSize = this.page.pageSize;
            this.page.currentPage = val;
            this.searchForm.pageNum = val;
            this.findPreCourseTagList(this.searchForm);
        },
        handleSizeChange(val) {
            this.searchForm.pageSize = val;
            this.page.pageSize = val;
            this.page.currentPage = 1;
            this.searchForm.pageNum = 1;
            this.findPreCourseTagList(this.searchForm);
        },
        search() {
            this.searchForm.pageSize = this.page.pageSize;
            this.searchForm.pageNum = 1;
            this.findPreCourseTagList(this.searchForm);
        },
        findPreCourseTagList(data) {
            if (!this.$checkMinor()) return;
            findPrerequisiteCourseTagList(data).then(res => {
                if (res.code == 200) {
                    const dataList = res.data;
                    if (dataList.list && dataList.list.length > 0) {
                        dataList.list.forEach(e => {
                            e.createDate = !e.createDate
                                ? null
                                : INDEX.parseTime(e.createDate);
                        });
                    } else {
                        dataList.list = [];
                    }

                    this.tableData = dataList.list;
                    this.page.currentPage = res.data.pageNum_;
                    this.page.totalPage = res.data.total_;
                }
            });
        },
        //选择学院后级联出先修课列表
        queryCourse() {
            // this.options.courses = [];
            // this.tagForm.courses = [];
            // if (!!this.tagForm.faculty) {
            //     let param = {
            //         faculty: this.tagForm.faculty,
            //         keyWord: ''
            //     }
            //     queryCourseInfo(param).then(res => {
            //         if (res.code == 200 && res.data.length > 0) {
            //             const list = res.data;
            //             list.forEach(e => {
            //                 e.label = `${e.label}(${e.value})`;
            //             });
            //             this.options["courses"] = list;
            //         }
            //     });
            // }
        },
        // _coursesData(data) {
        //     for (let key = 0; key < data.length; key++) {
        //         this.options["courses"].push({
        //             value: data[key].code,
        //             label: data[key].name
        //         });
        //     }
        // },
        deleteTag(row) {
            let params = {
                prerequisiteTagId: row.prerequisiteTagId
            };
            this.$confirm(
                "是否删除选中的先修课标签",
                this.$t("message.prompt"),
                {
                    confirmButtonText: this.$t("message.confirm"),
                    cancelButtonText: this.$t("message.cancel"),
                    type: "warning"
                }
            ).then(() => {
                deleteTagInfo(params).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: res.msg || '删除成功'
                        });
                        this.findPreCourseTagList({
                            tagName: "",
                            pageNum: 1,
                            pageSize: 20
                        });
                    }
                });
            });
        },
        //编辑
        handleClick(row) {
            this.tagForm = {
                tagName: "",
                faculty: "",
                major: "",
                preCourseName: "",
                startStatus: true,
                courses: []
            };
            this.dialogTagVisible = true;
            this.updateButton = true;
            this.insertButton = false;
            this.dialogTiltle = 1;
            //将相应的数据插入对应的地方
            this.tagForm.oldTagName = row.prerequisiteTagName;
            this.tagForm.tagName = row.prerequisiteTagName;
            this.tagForm.faculty = row.collegeId + "";
            this.tagForm.courses = row.courseId && row.courseId.split(",");
            // queryCourseInfo(param).then(res => {
            //     if (res.code == 200 && res.data.length > 0) {
            //         const list = res.data;
            //         list.forEach(e => {
            //             e.label = `${e.label}(${e.value})`;
            //         });
            //         this.options["courses"] = list;
            //     }
            // });
            this.remoteMethod('', 'edit');
            this.tagForm.startStatus = row.majorFlag == 1 ? true : false;
            this.rowTagId = row.prerequisiteTagId;
            this.$refs.tagForm && this.$refs.tagForm.resetFields();
        },
        updateCourseTagInfo() {
             this.$refs.tagForm.validate(valid => {
                if (valid) {
                    let params = {
                        prerequisiteTagId: this.rowTagId,
                        tagName: this.tagForm.tagName,
                        oldTagName: this.tagForm.oldTagName,
                        collegeId: this.tagForm.faculty,
                        courseId: this.tagForm.courses.toString(),
                        tagFlag: this.tagForm.startStatus ? "1" : "0",
                        majorId: 0
                    };
                    updatePreCourseTagInfo(params).then(res => {
                        if (res.code == 200) {
                            this.dialogTagVisible = false;
                            this.$message({
                                type: "success",
                                message: "编辑成功"
                            });
                            this.findPreCourseTagList({
                                tagName: "",
                                pageNum: 1,
                                pageSize: 20
                            });
                        }
                    });
                }
             })
        },
        remoteMethod(query, type) {
            let flag = type == 'edit';
            if (flag || query !== '' && !!this.tagForm.faculty) {
                if (flag) {
                    this.queryCourses(query, flag);
                }else {
                    if (this.timer) {
                        clearTimeout(this.timer);
                    }
                    this.timer = setTimeout(() => {
                        this.queryCourses(query);
                        clearTimeout(this.timer);
                    }, 400)
                }
            }
            else {
                 this.options["courses"] = [];
            }
        },
        queryCourses(query, flag) {
            this.loading = true;
            let param = {
                faculty: this.tagForm.faculty,
                keyWord: query,
                codeList: [] 
            }
            if (flag) {
                param.codeList = this.tagForm.courses;
            }
            this.options["courses"] = [];
            queryCourseInfo(param).then(res => {
                this.loading = false;
                if (res.code == 200) {
                    let list = res.data || [];
                    list.forEach(e => {
                        e.label = `${e.label}(${e.value})`;
                    });
                    this.options["courses"] = list;
                }
            }).catch(() =>{
                this.loading = false;
                this.options["courses"] = []
            })

        }
    }
};
</script>
<style scoped>
.tagTitle {
    font-size: 18px;
    font-family: "微软雅黑";
    margin-bottom: 30px;
}
.divLeft {
    float: left;
}
.divRight {
    float: right;
}
.rightCol {
    margin-left: 1rem;
}
</style>



